<?php


namespace app\admin\controller\goods;


use app\common\controller\Adminbase;
use think\Db;

class Cate extends Adminbase
{
    protected $searchFields = 'name';

    protected function initialize()
    {
        parent::initialize();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $_list = Db::name('goods_categoty')
                ->order('sort desc')
                ->page($page, $limit)
                ->where($where)
                ->where('is_del', 0)
                ->select();
            $total = Db::name('goods_categoty')
                ->where($where)
                ->count();
            $result = ["code" => 0, "count" => $total, "data" => $_list];
            return json($result);
        }
        return $this->fetch('goods/cate/index');
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data)) {
                $this->error('添加数据不能为空！');
            }
            $insert_data = array(
                'name' => $data['name'],
                'sort' => $data['sort'],
                'img' => $data['img']
            );
            $goods_id = Db::name('goods_categoty')->insertGetId($insert_data);
            if ($goods_id) {
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
        return $this->fetch('goods/cate/add');
    }

    public function setstateType()
    {
        $id = $this->request->param('id/d', 0);

        $status = $this->request->param('value/d');
        if (Db::name('goods_categoty')->where('id', $id)->update(['status' => $status])) {

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //删除
    public function del()
    {

        $ids = $this->request->param('ids/a', null);

        try {
            foreach ($ids as $id) {
                Db::name('goods_categoty')->where('id', $id)->update([
                    'is_del' => 1,
                ]);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }

        $this->success('删除成功！');
    }

    //编辑信息
    public function edit()
    {
        if ($this->request->isPost()) {

            $data = $this->request->post();

            $datas['name'] = $data['name'];

            $datas['sort'] = $data['sort'];
            $datas['img'] = $data['img'];

            $stmt = Db::name('goods_categoty')->where('id', $data['id'])->update($datas);
            $this->success('操作成功！');
        } else {
            $id = $this->request->param('id/d', 0);

            $data = Db::name('goods_categoty')->find($id);

            $this->assign('data', $data);

            return $this->fetch('goods/cate/edit');
        }
    }
}